<template>
  <div class="organization-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h1>机构管理</h1>
        </div>
      </template>

      <!-- 创建机构按钮和搜索框 -->
      <div class="header-actions">
        <el-button type="primary" @click="openDialog">创建机构</el-button>
        <el-input v-model="searchName" placeholder="请输入机构名称" style="width: 300px; margin-left: 20px"
          @input="handleSearch">
          <template #append>
            <el-button @click="clearSearch">清除</el-button>
          </template>
        </el-input>
      </div>

      <!-- 机构列表 -->
      <el-table :data="organizations.content" border stripe style="width: 100%" @row-click="viewOrganization">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="机构名称" />
        <el-table-column prop="type" label="机构类型" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" @click.stop="editOrganization(row)"></el-button>
            <el-button type="danger" :icon="Delete" @click.stop="deleteOrganization(row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
        :total="organizations.totalElements" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

      <!-- 增加/编辑机构对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑机构' : '创建机构'">
        <el-form :model="form" label-width="120px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="机构名称">
                <el-input v-model="form.name" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="机构类型">
                <el-select v-model="form.type" placeholder="请选择机构类型">
                  <el-option label="私人企业" value="私人企业" />
                  <el-option label="国有企业" value="国有企业" />
                  <el-option label="政府机关" value="政府机关" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '../axios';
import { ElMessage } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';

// 机构列表
const organizations = ref({
  content: [], // 当前页的机构数据
  totalElements: 0, // 总数据量
  size: 5, // 每页大小
  number: 1, // 当前页码（从 1 开始）
});

// 表单数据
const form = ref({
  id: null,
  name: '',
  type: '', // 初始值为空字符串
});

// 对话框是否可见
const dialogVisible = ref(false);

// 是否为编辑模式
const isEditMode = ref(false);

// 分页相关状态
const currentPage = ref(1); // 当前页码（从 1 开始）
const pageSize = ref(5); // 每页大小

// 搜索关键字
const searchName = ref('');

// 获取所有机构
const fetchOrganizations = async (page = 1, size = 5, name = '') => {
  try {
    const response = await axios.get('/organizations/search', {
      params: { page, size, name },
    });
    organizations.value = response.data;
  } catch (error) {
    ElMessage.error('获取机构列表失败');
  }
};

// 打开对话框
const openDialog = () => {
  isEditMode.value = false; // 设置为创建模式
  form.value = { id: null, name: '', type: '' }; // 清空表单
  dialogVisible.value = true;
};

// 清除搜索
const clearSearch = () => {
  searchName.value = ''; // 清空搜索框内容
  fetchOrganizations(1, pageSize.value); // 重新加载所有数据
};

// 编辑机构
const editOrganization = (row) => {
  isEditMode.value = true; // 设置为编辑模式
  form.value = { ...row }; // 填充表单
  dialogVisible.value = true;
};

// 表单验证
const validateForm = () => {
  if (!form.value.name || !form.value.type) {
    ElMessage.error('请填写所有必填字段');
    return false;
  }
  return true;
};

// 提交表单（创建或更新）
const submitForm = async () => {
  if (!validateForm()) {
    return; // 如果表单验证失败，直接返回
  }
  try {
    if (isEditMode.value) {
      // 更新机构
      const response = await axios.put(`/organizations/${form.value.id}`, form.value);
      const index = organizations.value.content.findIndex((org) => org.id === form.value.id);
      if (index !== -1) {
        organizations.value.content.splice(index, 1, response.data);
      }
      ElMessage.success('机构更新成功');
    } else {
      // 创建机构
      const response = await axios.post('/organizations', form.value);
      organizations.value.content.push(response.data);
      ElMessage.success('机构创建成功');
    }
    dialogVisible.value = false; // 关闭对话框
    fetchOrganizations(currentPage.value, pageSize.value, searchName.value); // 刷新当前页的机构列表
  } catch (error) {
    ElMessage.error(error.response?.data || '操作失败');
  }
};

// 查看机构详情
const viewOrganization = (row) => {
  ElMessage.info(`查看机构：${row.name}`);
};

// 删除机构
const deleteOrganization = async (id) => {
  try {
    await axios.delete(`/organizations/${id}`);
    organizations.value.content = organizations.value.content.filter((org) => org.id !== id);
    ElMessage.success('机构删除成功');
  } catch (error) {
    ElMessage.error('机构删除失败');
  }
};

// 处理每页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchOrganizations(1, size, searchName.value); // 每页大小变化时，加载第一页数据
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchOrganizations(page, pageSize.value, searchName.value); // 加载对应页的数据
};

// 处理搜索
const handleSearch = () => {
  if (searchName.value.trim() === '') {
    fetchOrganizations(1, pageSize.value); // 如果搜索框为空，加载所有数据
  } else {
    fetchOrganizations(1, pageSize.value, searchName.value); // 否则，执行模糊查询
  }
};

// 初始化时加载第一页数据
onMounted(() => {
  fetchOrganizations();
});
</script>

<style scoped>
.organization-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.card-header {
  text-align: center;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
::v-deep.el-table th,
::v-deep.el-table td {
  height: 40px;
  line-height: 40px;
  text-align: center;
}
</style>